package 文件小程序;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:目录的遍历使用listFile进行循环遍历
 * User: lenovo
 * Date: 2022-10-17
 * Time: 14:05
 */
public class demoa1 {
    public static void main(String[] args) throws IOException {
        //1.输入路径名
        System.out.println("请输入路径名:");
        Scanner scanner = new Scanner(System.in);
        File rootDir = new File(scanner.next());
        //判断输入的内容是否为目录
        if(!rootDir.isDirectory()){
            return;
        }
        //输入要查找的文件名
        System.out.println("请输入要查找的文件名:");
        String toDelete  = scanner.next();
        //2.遍历目录,关键在于listFiles方法
        scan(rootDir,toDelete);

    }

    private static void scan(File rootDir, String toDelete) throws IOException {
        System.out.println("当前文件位置:"+rootDir.getCanonicalPath());
        File[] files = rootDir.listFiles();
        //没有文件
        if(files == null){
            return;
        }
        //有文件,判断是目录还是文件
        for (File f: files) {
            //如果是目录继续遍历
            if(f.isDirectory()){
                scan(f,toDelete);
            }else{
                //如果是文件,则检查文件名
                check(f,toDelete);

            }
        }
    }

    private static void check(File f, String toDelete) throws IOException {
        if(f.getName().contains(toDelete)){
            System.out.println("在"+f.getCanonicalPath()+"里找到了"+f.getName()+"是否删除?(y/n)");
            Scanner scanner = new Scanner(System.in);
            if(scanner.next().equals("y") || scanner.next().equals("Y")){
                f.delete();
            }
        }
    }
}
